package cn.yunbamboos.mybatis.mapping.methods.generate;

import cn.yunbamboos.exception.AppException;
import cn.yunbamboos.mybatis.mapping.methods.BaseMethod;
import cn.yunbamboos.mybatis.metadata.TableInfo;
import cn.yunbamboos.mybatis.metadata.TablePrimaryKeyInfo;
import org.apache.ibatis.builder.StaticSqlSource;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.ResultMap;
import org.apache.ibatis.mapping.SqlCommandType;
import org.apache.ibatis.mapping.SqlSource;
import org.apache.ibatis.session.Configuration;

import java.util.ArrayList;
import java.util.List;

public abstract class GenerateIdMethod extends BaseMethod {

    public GenerateIdMethod(String methodName, Configuration configuration, TableInfo tableInfo) {
        super(methodName, configuration, tableInfo, SqlCommandType.SELECT);
    }

    @Override
    protected SqlSource getSqlSource() {
        List<TablePrimaryKeyInfo> pks = this.tableInfo.getPrimaryKeyList();
        if (pks.size() == 1) {
            TablePrimaryKeyInfo pk = pks.getFirst();
            String sql = "select coalesce ( max( `" + pk.getColumn() + "` ), 0 )+ 1  from `" + this.tableInfo.getTableName() + "`";
            return new StaticSqlSource(configuration, sql);
        }
        throw AppException.c("该表({})不支持自动生成主键", tableInfo.getTableName());
    }

    @Override
    protected MappedStatement.Builder getMappedStatementBuilder() {
        MappedStatement.Builder builder = super.getMappedStatementBuilder();
        List<ResultMap> resultMaps = new ArrayList<>();
        ResultMap inlineResultMap = new ResultMap.Builder(configuration, tableInfo.getMapperType().getName() + "-Inline", this.getResultClass(), new ArrayList<>(), null).build();
        resultMaps.add(inlineResultMap);
        builder.resultMaps(resultMaps);
        return builder;
    }

    protected abstract Class<?> getResultClass();
}
